import React, { Suspense } from 'react';
import ReactDOM from 'react-dom'
import 'lib-flexible'
import { HashRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import { PersistGate } from 'redux-persist/es/integration/react'
import { store, persistor } from '@store'
import { AliveScope } from 'react-activation'
import { getParamsString } from './utils'
import 'antd-mobile/dist/antd-mobile.css'
import './assets/css/index.css'

import { isApply, getWxCode, getWxUserInfo, selectOwner } from '@api'
import { fetchAddressAction, updateAppConfigAction } from '@store/actionCreators'
import Into from './page/Authentication/children/Into'
import { AppRouter } from './router'
import { ComponentLoading } from 'components/loading'

import * as Sentry from "@sentry/react";
import { Integrations } from "@sentry/tracing";
import Tabbar from './components/tabbar';
import NaviGationBar from './components/util';


/**
 * isBind  是否显示 解绑菜单 默认不显示
 * host   当前域名
 * authUniacid  授权公众号的 uniacid
 * appletOpenid  用户小程序openid
 * username: 
 * uniacid:  用户id
 * code: 微信授权code
 * isApplet 小程序环境判断
 * isApplys  是否入驻
 * goodsid 用户分享出去时的商品详情 商品id
 * groupid 用户分享出去的团 id
 */




const env =  true || process.env.NODE_ENV === 'development' ? true : false
let isBind = false
let host = window.location.host
let authUniacid = host === 'dev.lexiangpingou.cn' ? 53 : 33  // 授权公众号 uniacid
let appletOpenid = getParamsString('openid')  // 小程序
let username = getParamsString('username')
let uniacid = getParamsString('uniacid')
let code = getParamsString('code')
let isApplet = false
let isApplets = window.__wxjs_environment === 'miniprogram'
const goodsid = getParamsString('goodsid')
const groupid = getParamsString('groupid')


if (isApplets === true) {
  isApplet = true
}
let localAppConfig = JSON.parse(localStorage.getItem('appConfig'))
if (uniacid) {
  localStorage.setItem('localUniacid', JSON.stringify(uniacid))
}
if (goodsid || groupid) {
  localStorage.setItem('shareParams', JSON.stringify({
    goodsid,
    groupid
  }))
}

const App = async () => {
  let isApplys = await isApply(uniacid)
  if (!localAppConfig) {
    // 缓存中没有信息 需要授权
    if (code) {
      // 授权跳转成功
      let wxUserInfo = await getWxUserInfo({ uniacid: authUniacid, code: code })
      localStorage.setItem('appConfig', JSON.stringify(wxUserInfo))
      store.dispatch(fetchAddressAction)

      // 查询该微信用户是否是账号持有者
      let owner = await selectOwner({ uniacid: uniacid, appletOpenid })

      isBind = owner.isBind
      let isYou = owner.isYou

      store.dispatch(updateAppConfigAction({ uniacid, isApplys, username, isApplet, appletOpenid, isBind, isYou, userInfo: wxUserInfo }))

      inApp(isApplys)
    } else {
      if (env) {
        // 开发环境
        inApp(isApplys)
        store.dispatch(fetchAddressAction)
        store.dispatch(updateAppConfigAction({ uniacid, isApplys, username, isApplet, appletOpenid, isBind: true, isYou: false, userInfo: localAppConfig }))

      } else {
        // 还没有进行跳转
        let url = await getWxCode(authUniacid)
        window.location.href = url
      }
    }

  } else {
    // 近期已经授权过了 ， 但是需要 检查是否 与 账户关联
    store.dispatch(fetchAddressAction) // 跟新地址

    // 查询该微信用户是否是账号持有者
    let owner = await selectOwner({ uniacid: uniacid, appletOpenid: appletOpenid })

    isBind = owner.isBind
    let isYou = owner.isYou
    store.dispatch(updateAppConfigAction({ uniacid, isApplys, username, isApplet, appletOpenid, isBind, isYou, userInfo: localAppConfig }))
    inApp(isApplys)
  }
}



function inApp(isApplys) {

  let newUrl
  let replaceCode = new RegExp('(^|&)code=([^&]*)(&|$)', 'i')
  let href = window.location.href
  console.log(window.location.href)

  if (href.search(/(goodsid|groupid)/) > 0) {
    const replaceShareParams = new RegExp('(^|&)(goodsid|groupid)=([^&]*)(&|$)', 'i')
    newUrl = href.replace(replaceCode, `&`).replace(replaceShareParams, '&') // 去code 后 去 goodsid 
  } else {
    newUrl = href.replace(replaceCode, `&`) // 去code
  }

  console.log(window.location.href)

  window.history.pushState({}, '', newUrl)

  if (!env) {
    Sentry.init({
      dsn: "https://0c97f3c92d0d4ef088d603b8321f52ee@o512287.ingest.sentry.io/5611849",
      // release: "v1.0.3",
      autoSessionTracking: true,
      integrations: [
        new Integrations.BrowserTracing(),
      ],
      // We recommend adjusting this value in production, or using tracesSampler
      // for finer control
      tracesSampleRate: 1.0,
    });
  }

  // console.log('进入app 时：', store.getState().appConfig)

  // const AppConfigContext = React.createContext(store.getState().appConfig)



  

  ReactDOM.render(
    <Provider store={store}>
      <PersistGate persistor={persistor}>
        <HashRouter>
          <AliveScope>
            <Suspense fallback={<ComponentLoading />}>
              {/* <AppConfigContext.Provider value={ store.getState().appConfig }> */}
              {/* <NaviGationBar /> */}
              {isApplys === 1 && <AppRouter />}
              {isApplys === 1 && < Tabbar />}
              {isApplys === 0 && <Into />}
              {/* </AppConfigContext.Provider> */}
            </Suspense>
          </AliveScope>
        </HashRouter>
      </PersistGate>
    </Provider>
    ,
    document.getElementById('root')
  )

}

App()



